/**
 * 判断是否为空
 * @method isEmpty
 * @param  val
 * @return {boolean}
 */
const isEmpty = function (val) {
  return val === null || val === undefined || val === '' || val.length === 0 || JSON.stringify(val) === '{}'
}

/**
 * option对象属性的深拷贝
 */
const extendObject = (initalObj, finalObj) => {
  if (isEmpty(finalObj)) {
    return initalObj
  } else {
    for (let i in initalObj) {
      if (finalObj[i] === undefined) {
        finalObj[i] = initalObj[i]
      } else if (typeof initalObj[i] === 'object') {
        extendObject(initalObj[i], finalObj[i])
      }
    }
    return finalObj
  }
}

/**
 * 判断市场，由标志获取字段值
 */
const getMarketCode = function (stockCode) {
  if (stockCode.substring(0, 2) === 'SH') {
    return '1'
  } else if (stockCode.substring(0, 2) === 'SZ') {
    return '2'
  } else {
    return ''
  }
}

/**
 * 判断市场，由字段值获取标志
 */
const getMarketName = (exchangeType) => {
  if (typeof exchangeType === 'undefined') {
    return ''
  }
  if (exchangeType === 'SH') {
    return 'SH'
  } else if (exchangeType === 'SZ') {
    return 'SZ'
  } else if (Number(exchangeType) === 1) {
    return 'SH'
  } else {
    return 'SZ'
  }
}

/**
 * 日期格式化
 * yyyyMMdd >> yyyy/MM/dd
 */
const formatDateSlash = (strDate) => {
  strDate = strDate + ''
  if (!isNaN(strDate) && strDate.length === 8) {
    strDate = strDate.replace(/^(\d{4})(\d{2})(\d{2})$/, '$1/$2/$3')
  }
  return strDate
}

/**
 * 四舍五入
 * @param number 需要处理的数字
 * @param digits 小数位数
 */
const toFixed = function (number, digits) {
  if (number === '') {
    return ''
  }
  if (isNaN(number)) {
    return number
  }
  let object = Number(number)
  let result = object.toFixed(digits)

  if (result === '-0.00') { // 解决部分负数保留两位小数后，-0.00，0.00 页面样式不一致问题，如 -0.0000012
    result = '0.00'
  }

  return result
}

/**
 * 获取由一个多维数组的最大值、最小值、总数、平均值等等组成的对象
 */
const compute = (array) => {
  array = array.join(',').split(',') // 多维转一维
  let max = Math.max.apply({}, array)
  let min = Math.min.apply({}, array)
  let sum = 0
  for (let i = 0; i < array.length; i++) {
    if (!isNaN(array[i])) {
      sum += Number(array[i])
    }
  }
  sum = Number(toFixed(sum, 2))
  let avg = Number(toFixed(sum / array.length, 2))
  let halfavg = Number(toFixed(avg / 2, 2))
  let top = Number(toFixed((max + halfavg), 2))
  let bottom = Number(toFixed(((min - halfavg < 0) ? 0 : (min - halfavg)), 2))

  return {max, min, sum, avg, halfavg, top, bottom}
}

  /**
   * 工具类 获取url 参数
   * @method getUrlParam
   * @private
   */
const getUrlParam = (name) => {
  let url = decodeURI(location.search)
  let theRequest = {}
  if (url.indexOf('?') !== -1) {
    let str = url.substr(1)
    let strs = str.split('&')
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
    }
  }
  return theRequest[name]
}

export default {
  isEmpty,
  extendObject,
  getMarketCode,
  getMarketName,
  formatDateSlash,
  toFixed,
  compute,
  getUrlParam
}
